package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.ui.AbstractSpinerAdapter.IOnItemSelectListener;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.util.List;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.Utils.RecycleBitmap;

/**
 * 银行卡信息，Created by Administrator on 2016/5/12.
 */

public class BankCardInfoViewHe extends LFView implements View.OnClickListener, MainActivity.OnActivityReturnBitmap,
        IOnItemSelectListener, ILFMsgListener {
    private Context context = null;
    private View view = null;
    private Dialog processDialog;
    private BaseApplication mApplication;
    private ImageView iv_bankcarinfo1;
    private ImageView iv_bankcarinfo2;
    private ImageView iv_bankcarinfo3;
    private int ImageType = -2;
    private String bImage;
    private Bitmap imgeBitmap;
    private String appCaseno;
    private EntityBean bankinfoBean;//对方的车主信息的bean
    private String carownphone2;
    private String dutytype2;
    private String carownname2;
    private String casecarno2;
    private String feepaymoney2;
    private TextView et_bankinfo1;
    private EditText et_bankname1;
    private EditText et_bankinfo2;
    private LinearLayout ll_1;
    private List<String> carnoList;
    private LinearLayout hn_btn_back;
    private TextView tv_title;
    private Button btn_bankcardinfo_he;
    private Button btn_bankcardinfo_he2;
    private EditText et_bf_bank_hisname;

    public BankCardInfoViewHe(Context c, EntityBean bankinfoBean, String appCaseno, List<String> carnoList) {
        super(c);
        this.context = c;
        this.mApplication = ((MainActivity) c).getAppData();
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
        this.appCaseno = appCaseno;
        this.bankinfoBean = bankinfoBean;
        this.carnoList = carnoList;
    }

    public BankCardInfoViewHe(Context c) {
        super(c);
        this.context = c;
        this.mApplication = ((MainActivity) c).getAppData();
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {

    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        ((MainActivity) context).initHelpView(view, appCaseno);
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_bankcardinfohe, null);
        btn_bankcardinfo_he = (Button) view.findViewById(R.id.btn_bankcardinfo_he);
        btn_bankcardinfo_he2 = (Button) view.findViewById(R.id.btn_bankcardinfo_he2);
        iv_bankcarinfo1 = (ImageView) view.findViewById(R.id.iv_bankcarinfo1);//对方银行卡
        iv_bankcarinfo2 = (ImageView) view.findViewById(R.id.iv_bankcarinfo2);
        iv_bankcarinfo3 = (ImageView) view.findViewById(R.id.iv_bankcarinfo3);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("银行卡信息");
        ll_1 = (LinearLayout) view.findViewById(R.id.ll_1);
        //对方银行
        et_bankinfo1 = (TextView) view.findViewById(R.id.et_bankinfo1);
        et_bankname1 = (EditText) view.findViewById(R.id.et_bankname1);
        et_bankinfo2 = (EditText) view.findViewById(R.id.et_bankinfo2);
        et_bf_bank_hisname = (EditText) view.findViewById(R.id.et_bf_bank_hisname);

        //对方数据
        carownphone2 = (String) bankinfoBean.get("carownphone");
        dutytype2 = (String) bankinfoBean.get("dutytype");
        carownname2 = (String) bankinfoBean.get("carownname");
        casecarno2 = (String) bankinfoBean.get("casecarno");
        feepaymoney2 = (String) bankinfoBean.get("feepaymoney");
        et_bf_bank_hisname.setText(carownname2);

        //统计区分
        String text = context.getResources().getString(R.string.bankinfo_commit);
        btn_bankcardinfo_he.setText(CommontUtils.changeStrColor(text, "提交", Color.WHITE));
    }

    private void regEvent(boolean b) {
        if (null != btn_bankcardinfo_he) {
            btn_bankcardinfo_he.setOnClickListener(b ? this : null);
        }
        if (null != btn_bankcardinfo_he2) {
            btn_bankcardinfo_he2.setOnClickListener(b ? this : null);
        }
        //对方
        if (null != iv_bankcarinfo1) {
            iv_bankcarinfo1.setOnClickListener(b ? this : null);
        }
        if (null != iv_bankcarinfo2) {
            iv_bankcarinfo2.setOnClickListener(b ? this : null);
        }
        if (null != iv_bankcarinfo3) {
            iv_bankcarinfo3.setOnClickListener(b ? this : null);
        }
        if (null != ll_1) {
            ll_1.setOnClickListener(b ? this : null);
        }
        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
        if (b) {
            addILFMsgListener(this);
        } else {
            removeILFMsgListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hn_btn_back:
                OnDestroy();
                closeForm();
                break;
            //对方
            case R.id.iv_bankcarinfo1:
                ImageType = 0;
                getCamera("身份证正面", null, R.mipmap.sfz_8);
                break;
            case R.id.iv_bankcarinfo2:
                ImageType = 1;
                getCamera("身份证反面", null, R.mipmap.sfz_7);
                break;
            case R.id.iv_bankcarinfo3:
                ImageType = 2;
                getCamera("银行卡正面", null, R.mipmap.card_6);
                break;
            case R.id.ll_1:
                UiUtil.showSelectPopWindow(context, carnoList, this, ll_1, true);
                break;
            case R.id.btn_bankcardinfo_he:
                if (!checkData()) {
                    return;
                }
                //判断是否完成拍照
                for (int i = 0; i < 3; i++) {
                    if (null == mBItmap[i]) {
                        UiUtil.showToast(context, "请完成拍照后提交");
                        return;
                    }
                }
                submitBankCardInfo();
                break;
            case R.id.btn_bankcardinfo_he2:
                messageRemind();
                break;

        }
    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {//点击返回按键
            ((MainActivity) context).backToMainView();
        }
        return null;
    }

    //检测输入的内容是否正确
    private boolean checkData() {
        String name = et_bf_bank_hisname.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            UiUtil.showToast(context, "请输入被保险人姓名");
            return false;
        }
        String cardType = et_bankinfo1.getText().toString().trim();
        if (TextUtils.isEmpty(cardType)) {
            UiUtil.showToast(context, "请选择银行卡类型");
            return false;
        }
        String cardno = et_bankname1.getText().toString().trim();
        if (TextUtils.isEmpty(cardno)) {
            UiUtil.showToast(context, "请输入正确的银行卡号");
            return false;
        }
        String cardAdd = et_bankinfo2.getText().toString().trim();
        if (TextUtils.isEmpty(cardAdd)) {
            UiUtil.showToast(context, "请输入正确的开户地址");
            return false;
        }
        return true;
    }

    //启动相机
    public void getCamera(String title, String titleBottom, int resourceId) {
        //判断是否有权限
        if (!PermissionHelper.checkCameraPermissions(context)) {
            return;
        }
        Intent intent = new Intent(getContext(), HeNanSurfaceViewCameraActivity.class);
        Bundle bundle = new Bundle();

        if (!StringUtils.isEmpty(title)) {
            bundle.putString("title", title);
        }
        if (!StringUtils.isEmpty(titleBottom)) {
            bundle.putString("titleBottom", titleBottom);
        }

        if (resourceId != 0) {
            bundle.putInt("backGroundResourceId", resourceId);
        }
        intent.putExtras(bundle);

        if (context instanceof MainActivity) {
            ((MainActivity) context).startActivityForResult(intent, 112);
        }
    }

    //给保险公司发送图片数据
    private void submitImageInfo(String imageInfo) {
        String uid = mApplication.getKckpName();
        String token = mApplication.getToken();
        ApiImpI.getInstance(context.getApplicationContext()).submitImageInfo(appCaseno, uid, token, imageInfo, null);
    }

    //提交银行卡信息
    private void submitBankCardInfo() {
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
        bean.set("appcaseno", appCaseno);
        bean.set("uid", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        //对方照片上传
        bean.set("cardimg", CommontUtils.Bitmap2Bytes(mBItmap[0]));//身份证正面
        bean.set("cardbackimg", CommontUtils.Bitmap2Bytes(mBItmap[1]));//身份证反面
        bean.set("bankcardpic", CommontUtils.Bitmap2Bytes(mBItmap[2]));//银行卡正面
        EntityBean dfBean = new EntityBean();// 对方数据
        dfBean.set("carownname", et_bf_bank_hisname.getText().toString().trim());
        dfBean.set("carownphone", carownphone2); //手机号
        dfBean.set("casecarno", casecarno2); // 案件车牌号
        dfBean.set("bussisinsuredbkname", et_bankinfo1.getText().toString().trim()); // 开户行
        dfBean.set("bussisinsuredbkcardno", et_bankname1.getText().toString().trim());//卡号
        dfBean.set("banklocation", et_bankinfo2.getText().toString().trim());//开户地址
        bean.set("casecar", dfBean);

        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.KCKPSAVEBANKCARDINFO, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            submitImageInfo("1");
                            //进入审核界面
                            AccidentCheckView accidentcheckview = new AccidentCheckView(context, appCaseno, 3);
                            FrameworkManager.getInstance().showNewForm(context, accidentcheckview);
                        } else {
                            UiUtil.showToast(context, redes);
                        }

                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                        return;
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    //private ArrayList<Bitmap> mBitmapList = new ArrayList<Bitmap>();
    private Bitmap[] mBItmap = new Bitmap[3];

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode,
                                     Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            Bundle bundle = data.getExtras();
            bImage = bundle.getString("image");
            if (bImage == null) {
                return;
            }
            imgeBitmap = BitmapFactory.decodeFile(bImage);
            //将bitmap压缩为之前的二分之一大小
            Bitmap halfbitmap = bitmapNewWaH(imgeBitmap);
            mBItmap[ImageType] = halfbitmap;
            setPicToView();//显示图片
        }
    }

    /**
     * 判断将图片显示在哪里
     */
    private void setPicToView() {
        switch (ImageType) {
            //对方
            case 0:
                iv_bankcarinfo1.setImageBitmap(mBItmap[0]);
                break;
            case 1:
                iv_bankcarinfo2.setImageBitmap(mBItmap[1]);
                break;
            case 2:
                iv_bankcarinfo3.setImageBitmap(mBItmap[2]);
                break;
        }
    }

    @Override
    public void onItemClick(int pos, View view) {

        switch (view.getId()) {
            case R.id.ll_1:
                et_bankinfo1.setText(carnoList.get(pos));
                break;
            default:
                break;
        }

    }

    private Bitmap bitmapNewWaH(Bitmap imgeBitmap2) {
        int oldWidth = imgeBitmap2.getWidth();
        int oldHeight = imgeBitmap2.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f);
        Bitmap newbitmap = Bitmap.createBitmap(imgeBitmap2, 0, 0, oldWidth, oldHeight, matrix, true);
        return newbitmap;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        regEvent(false);
        view = null;
        bankinfoBean = null;
        if (null != imgeBitmap && !imgeBitmap.isRecycled()) {
            imgeBitmap.recycle();
        }
        imgeBitmap = null;
        mBItmap = null;
        RecycleBitmap.recycleImageView(iv_bankcarinfo1);
        RecycleBitmap.recycleImageView(iv_bankcarinfo2);
        RecycleBitmap.recycleImageView(iv_bankcarinfo3);
    }

    //对方不在，短信提醒
    private void messageRemind() {
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
        bean.set("appcaseno", appCaseno);
        bean.set("uid", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        EntityBean dfBean = new EntityBean();// 对方数据
        dfBean.set("carownname", carownname2);
        dfBean.set("carownphone", carownphone2); //手机号
        dfBean.set("casecarno", casecarno2); // 案件车牌号
        dfBean.set("bussisinsuredbkname", et_bankinfo1.getText().toString().trim()); // 开户行
        dfBean.set("bussisinsuredbkcardno", et_bankname1.getText().toString().trim());//卡号
        dfBean.set("banklocation", et_bankinfo2.getText().toString().trim());//开户地址
        bean.set("casecar", dfBean);

        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.SENDINPUTBANKMSG, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            //对方不在，回到首页
                            UiUtil.showToast(context, "已成功向对方发送提醒短信");
                            ((MainActivity) context).backToMainView();
                        } else {
                            UiUtil.showToast(context, redes);
                        }

                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                        return;
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

}
